package cn.cdutetc.foxwatch.exception;


import cn.cdutetc.foxwatch.pojo.Result;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

//全局异常处理器 会把返回结果返回给前端
@RestControllerAdvice

public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<Result> handlerException(Exception e) {
        e.printStackTrace();
        // 创建Result对象，检查异常对象的消息是否存在且长度大于 0 ：异常信息
        Result result = Result.error(!e.getMessage().isEmpty() ? e.getMessage() : "未知错误");
        // 使用ResponseEntity返回带有状态码的响应
        return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(MyException.class)
    public ResponseEntity<Result> handlerCustomException(MyException e) {
        e.printStackTrace();
        // 创建Result对象，检查异常对象的消息是否存在且长度大于 0 ：异常信息
        Result result = Result.error(e.getMessage());
        // 使用ResponseEntity返回带有状态码的响应
        return new ResponseEntity<>(result, HttpStatus.valueOf(e.getStatusCode()));
    }
}
